package dk.modified.radioonlineapp;

import java.util.ArrayList;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class MainActivity extends TabActivity implements OnScrollListener,
		OnTabChangeListener, TextWatcher, OnKeyListener, OnGlobalLayoutListener {//, SeekBar.OnSeekBarChangeListener {


//	@Override
//	protected void onPause() {
//		// TODO Auto-generated method stub
//		super.onPause();
//		System.gc();
//	}
//
//	@Override
//	protected void onResume() {
//		// TODO Auto-generated method stub
//		super.onResume();
//		System.gc();
//	}
//
//	@Override
//	protected void onDestroy() {
//		// TODO Auto-generated method stub
//		super.onDestroy();
//		
//		lwAll = null;
//		lwMost = null;
//		lwFav = null;
//		lwSearch = null;
//		datasource = null;
//		playerService = null;
//		
//		listRa = null;
//		adapterAll.clear();
//		adapterAll = null;
//		adapterMost = null;
//		adapterFav = null;
//		adapterSearch = null;
//		listRaMost = null;
//		listRaFav = null;
//		listRaSearch = null;
//		play.setImageDrawable(null);
//		play.setBackgroundDrawable(null);
//		stop.setImageDrawable(null);
//		stop.setBackgroundDrawable(null);
//		cmdSwitchGlobal.setImageDrawable(null);
//		cmdSwitchGlobal.setBackgroundDrawable(null);
//		cmdSwitchGlobal = null;
//		nowPlaying = null;
//		textBoxStat = null;
//		tabHost.removeAllViews();
//		imgLoading = null;
//		anim = null;
//		controlsBar.removeAllViews();
//		txtSearch = null;
//		handlerText = null;
//		handlerSearch = null;
//		url = null;
//		lastSearch = null;
//		activityRootView = null;
//		mcrypt = null;
//		JSONparser.clearStuff();
//		System.gc();
//	}

	private static final int ADD_RADIO_TO_FAV_LWALL = 0;
	private static final int DELETE_RADIO_FROM_FAV_LWALL = 1;
	private static final int ADD_RADIO_TO_FAV_LWMOST = 2;
	private static final int DELETE_RADIO_FROM_FAV_LWMOST = 3;
	private static final int DELETE_RADIO_FROM_FAV_LWFAV = 4;
	private static final int ADD_RADIO_TO_FAV_LWSEARCH = 5;
	private static final int DELETE_RADIO_FROM_FAV_LWSEARCH = 6;
	private RadioAdapter adapterAll;
	private RadioAdapter adapterMost;
	private RadioAdapter adapterFav;
	private RadioAdapter adapterSearch;
	private List<Radio> list;
	private int count = 20;
	private ListView lwAll;
	private ListView lwMost;
	private ListView lwFav;
	private ListView lwSearch;
	private CommentsDataSource datasource;
	public static Intent playerService;
	public static List<Radio> listRa;
	public static List<Radio> listRaMost;
	public static List<Radio> listRaFav;
	public static List<Radio> listRaSearch;
	public static ImageButton play;
	public static ImageButton stop;
	public static ImageButton cmdSwitchGlobal;
	public static TextView nowPlaying;
	public static TextView textBoxStat;
	public static TabHost tabHost;
	public static ImageView imgLoading;
	public static AnimationDrawable anim;
	private RelativeLayout controlsBar;
	private EditText txtSearch;
	/*public static TextView songTotalDurationLabel;
	public static TextView songCurrentDurationLabel;*/
	
	public static boolean searchGlobal;
	Handler handlerText = new Handler();
	Handler handlerSearch = new Handler();
	public static int id;
	public static String url;
	private String lastSearch;
	private View activityRootView;
	//public static SeekBar songProgressBar;
	//public static ViewGroup songProgressBar;
	MCrypt mcrypt = new MCrypt();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// All of the onCreate content is decided in these 4:
		initViews();
		setUpTabs();
		initData();
		uiUpdate();
		
		//com.google.ads.AdView adView = (com.google.ads.AdView)this.findViewById(R.id.adView);
	    //adView.loadAd(new AdRequest());

	}
	
	@Override
	protected void onPause() {
		// hide keyboard when its shown on the search tab
	    hideKeyboard();
	    super.onPause();
	}
	
	
	// All ListViews use this, because of very similar functionality.
	// It uses the position of the clicked item in the ListView, the List<Radio>
	// used in the specific ListView and a boolean to know if global search is
	// on.
	// It handles the starting and stopping of streams, updating GUI (switching
	// of buttons and setting texts) and keeps the database updated with played
	// count and active radio.
	private void lwClicked(int position, List<Radio> radioList, boolean boo) {
		if (position >= 0) {
			int clickedID = radioList.get(position).getId();
			datasource.Open();
			try {
				if (isRadioServiceRunning(this) == true
						&& clickedID == datasource.GetRadioActive()) {
					stopService(playerService);
					stop.setVisibility(View.GONE);
					play.setVisibility(View.VISIBLE);
					textBoxStat.setText(getString(R.string.textBoxStatStop));
					imgLoading.setVisibility(View.GONE);
				} else {
					int pos = radioList.get(position).getId();
					if (boo) {
						datasource.OneUp(pos);
						datasource.UpdateActiveID(pos);
					} else {

						url = new String(mcrypt.decrypt(radioList.get(position)
								.getUrl())).trim();
						id = radioList.get(position).getId();
					}

					String md5 = ByteConverter.MD5(pos
							+ radioList.get(position).getSlug());
					ByteConverter.postData(md5, pos, true);

					if (isRadioServiceRunning(this) == true) {
						stopService(playerService);
					}
					stop.setVisibility(View.VISIBLE);
					play.setVisibility(View.GONE);
					startService(playerService);

					nowPlaying.setText(radioList.get(position).getName());
					textBoxStat.setText(getString(R.string.textBoxStatLoad));
					anim.start();
					imgLoading.setVisibility(View.VISIBLE);
					
					/*RangeSeekBar<Long> seekbar = new RangeSeekBar<Long>(0L, 600000L, getApplicationContext());
					seekbar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Long>() {
				        @Override
				        public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Long minValue, Long maxValue) {
				                // handle changed range values
				                //Log.i(TAG, "User selected new date range: MIN=" + new Date(minValue) + ", MAX=" + new Date(maxValue));
				        }
					});
					
					songProgressBar = (ViewGroup) findViewById(R.id.songProgressBar);
					songProgressBar.addView(seekbar);*/
					
					// set Progress bar values
		           // songProgressBar.setProgress(0);
		            //songProgressBar.setMax(100);
		 
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			datasource.Close();
		}
	}
	
	

	// Used for closing of the on screen keyboard.
	private void hideKeyboard() {
		try {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0); 
		}
		catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		showAddmob();	
	}
	
	private void showKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		getCurrentFocus().requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		hideAddmob();
		
	}
	
	private void hideAddmob() {
		com.google.ads.AdView ad = (com.google.ads.AdView) findViewById(R.id.adView);
		if (ad != null) ad.setVisibility(View.GONE);
		
	}
	
	private void showAddmob() {
		com.google.ads.AdView ad = (com.google.ads.AdView) findViewById(R.id.adView);
		if (ad != null) ad.setVisibility(View.VISIBLE);
		
	}
	
	
	private void setTabColor() {
		for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
	    {
			tabHost.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.white)); //unselected
	    }
		tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.green)); // selected
	}

	// Clears listRaSearch (the list linked to the search tabs ListView), and
	// refills it with the radios from a local search using the text in
	// txtSearch (EnterText).
	// Ends with notifyDataSetChanged to update ListView.
	private void searchLocal() {
		if(txtSearch.getText().length() >= 2){
			datasource.Open();
			listRaSearch.clear();
			try {
				listRaSearch.addAll(datasource.SearchLocal(txtSearch.getText()
						.toString().trim()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			adapterSearch.notifyDataSetChanged();
			datasource.Close();
		}	
	}

	// Same as localSearch, but uses JSON to make a global search.
	private void searchGlobal() {
		handlerText.removeCallbacksAndMessages(null);
		listRaSearch.clear();
		JSONparser.clearStuff();
		handlerText.postDelayed(new Runnable() {
			public void run() {

				String url = "https://itunedradio.com/app_access/json_parser.php?q=";
				String search = txtSearch.getText().toString().trim();
				String resultString = search.replaceAll("[^\\p{L}\\p{Nd}]", " ");
				String newString = resultString.replace(' ', '+');
				search = url + newString; 
				Log.d("temp", newString);
				listRaSearch.addAll(JSONparser.getRadios(search, false));
				adapterSearch.notifyDataSetChanged();
			}
		}, 0);

	}

	// Downloads the image of the clicked radio station
	private void downloadImage(RadioAdapter adapter, ImageView imgView,
			List<Radio> radios, int position) {
		adapter.loadBitmap(imgView, radios.get(position).getSlug(), true);
	}

	// Looks if a service is running, with the same class name of the
	// RadioService-class.
	public static boolean isRadioServiceRunning(Context context) {
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (RadioService.class.getName().equals(
					service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	// /////////////////
	// CLICKS //////////
	// /////////////////

	// When a ListView is clicked, lwClicked() is used, with params relevant to
	// the specific ListView clicked.
	private void ListViewOnClick() {
		lwAll.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				hideKeyboard();
				lwClicked(position, listRa, true);
				downloadImage(adapterAll,
						(ImageView) view.findViewById(R.id.itemRowImg), listRa,
						position);
			}
		});

		lwMost.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				hideKeyboard();
				lwClicked(position, listRaMost, true);
			}
		});

		lwFav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				hideKeyboard();
				lwClicked(position, listRaFav, true);
			}
		});

		lwSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// downloadImage(adapterSearch,downloadImage,listRaSearch,position);
				hideKeyboard();
				//Toast.makeText(getApplicationContext(), "hej", Toast.LENGTH_LONG).show();

				if (!searchGlobal)
					lwClicked(position, listRaSearch, true);
				else {
					lwClicked(position, listRaSearch, false);
				}
			}
		});
	}

	// When the play button is clicked a service for the radio is started.
	// It gets replaced with the stop button, sets status text to loading, hides
	// the keyboard and starts the loading animation.
	// The loading animation is later stopped and hidden by the service, when
	// the stream starts playing.
	public void playStreamClick(View v) {
		
		try{
			datasource.Open();
			if(datasource.GetActiveURL().trim().length() > 4){
				stop.setVisibility(View.VISIBLE);
				play.setVisibility(View.GONE);
				playerService = new Intent(this, RadioService.class);
				textBoxStat.setText(getString(R.string.textBoxStatLoad));
				startService(playerService);
				anim.start();
				imgLoading.setVisibility(View.VISIBLE);
				hideKeyboard();
			} else {
				Toast.makeText(getApplicationContext(),
						getString(R.string.textBoxDef), Toast.LENGTH_SHORT).show();
				searchLocal();
			}
			datasource.Close();
		} catch(Exception ex) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.textBoxDef), Toast.LENGTH_SHORT).show();
			datasource.Close();
		}
		
	}

	// Stops the running service. Switches the stop button with the play button,
	// test status text to stopped and removes loading animation and hides the
	// keyboard.
	public void stopStreamClick(View v) {
		play.setVisibility(View.VISIBLE);
		stop.setVisibility(View.GONE);
		playerService = new Intent(this, RadioService.class);
		textBoxStat.setText(getString(R.string.textBoxStatStop));
		imgLoading.setVisibility(View.GONE);
		stopService(playerService);
		hideKeyboard();
	}

	// Button for switching global search on/off. Changes button image, sets the
	// global search state and clears listRaSearch and updates ListView.
	// A toast is show to inform user of event.
	public void switchGlobalClick(View v) {
		if (searchGlobal) {
			cmdSwitchGlobal.setBackgroundResource(R.raw.global_icon_gray);
			searchGlobal = false;
			Toast.makeText(getApplicationContext(),
					getString(R.string.globalIsOff), Toast.LENGTH_SHORT).show();
			searchLocal();
		} else {
			cmdSwitchGlobal.setBackgroundResource(R.raw.global_icon);
			searchGlobal = true;
			Toast.makeText(getApplicationContext(),
					getString(R.string.globalIsOn), Toast.LENGTH_SHORT).show();
			searchGlobal();
		}
		// listRaSearch.clear();
		// adapterSearch.notifyDataSetChanged();
	}

	// When search button is clicked, and the content on txtSearch (EditText)
	// and string lastSearch is not the same and txtSearch contains >= 3 chars,
	// then:
	// A localSearch or globalSearch is run, depending on global search setting.
	// if txtSearch is less than 3 chars, a toast is shown to inform user.
	public void searchClick(View v) throws Exception {
		if (txtSearch.getText().toString().trim() == lastSearch || txtSearch.getText().toString().length() == 0) {
			if (txtSearch.getText().toString().trim().length() >= 2) {
				if (!searchGlobal) {
					searchLocal();
				} else if (searchGlobal) {
					searchGlobal();
				}
				lastSearch = txtSearch.getText().toString().trim();
				hideKeyboard();
			} else {
				Toast.makeText(getApplicationContext(),
						getString(R.string.textTooShort), Toast.LENGTH_LONG)
						.show();
			}
		} else {
			Toast.makeText(getApplicationContext(),
					getString(R.string.sameSearch), Toast.LENGTH_LONG)
					.show();
		}
	}

	// ////////////////////
	// @Override //////////
	// ////////////////////

	// This is what happens while scrolling is done. Nothing.
	// This is to keep any unnecessary work from being done while scrolling.
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
	}

	// After scrolling is done more items is loaded into the ListView of the all
	// tab, if close to the bottom of the ListView
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

		if (scrollState == SCROLL_STATE_IDLE) {
			if (lwAll.getLastVisiblePosition() >= lwAll.getCount() - 15) {
				if (list.size() > count) {

					if (list.size() < count + 20) {
						count = list.size();
					}
					adapterAll.clear();
					List<Radio> test = list.subList(0, count);
					for (int i = 0; i < test.size(); i++) {
						adapterAll.add(test.get(i));
					}
					adapterAll.notifyDataSetChanged();
					adapterAll.getCount();
					count = count + 20;
				}
			}
		}
	}

	// If ender on the on screen keyboard is pressed, a search os done (if
	// txtSearch (EditText) has more than 2 chars) and the keyboard is closed.
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if ((event.getAction() == KeyEvent.ACTION_DOWN)
				&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
			if (txtSearch.getText().toString().trim().length() >= 2) {

				if (!searchGlobal) {
					searchLocal();
				} else if (searchGlobal) {
					searchGlobal();
				}

			} else {
				Toast.makeText(getApplicationContext(),
						getString(R.string.textTooShort), Toast.LENGTH_LONG)
						.show();
			}

			hideKeyboard();
			showAddmob();
		}
		return false;
	}
	

	// When changing tabs, the newly selected tabs LitView is updated.
	@Override
	public void onTabChanged(String tabId) {
		hideKeyboard();
		setTabColor();
		
		switch (tabHost.getCurrentTab()) {
		case 0:
			adapterAll.notifyDataSetChanged();
			break;
		case 1:
			datasource.Open();
			listRaMost.clear();
			try {
				listRaMost.addAll(datasource.SelectMostRadiosFromDB());
				adapterMost.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
			}
			datasource.Close();
			adapterMost.notifyDataSetChanged();
			break;
		case 2:
			datasource.Open();
			listRaFav.clear();
			try {
				listRaFav.addAll(datasource.SelectFavRadiosFromDB());
			} catch (Exception e) {
				e.printStackTrace();
			}
			datasource.Close();
			break;
		case 3:
			txtSearch.requestFocus();
			//imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
			showKeyboard();
			adapterSearch.notifyDataSetChanged();
			break;
		}
	}

	// Gives access to settings.
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.menu_settings:
			Intent i = new Intent(this, UserSettingActivity.class);
			startActivityForResult(i, 1);
			break;
			
		case R.id.menu_about:
			Intent i1 = new Intent(this, AboutScreen.class);
			startActivity(i1);
			break;
		}
		return true;
	}

	// When holding down on a ListView item, a dialog will show, giving the
	// option to add that radio to favorites (or remove if already there).
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		datasource.Open();

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

		if (v == lwAll) {
			menu.setHeaderTitle(listRa.get(info.position).getName());
			if (!datasource.DoesFavExists(listRa.get(info.position).getId())) {
				menu.add(Menu.NONE, ADD_RADIO_TO_FAV_LWALL, 0,
						getString(R.string.addToFav));
			} else {
				menu.add(Menu.NONE, DELETE_RADIO_FROM_FAV_LWALL, 1,
						getString(R.string.deleteFromFav));
			}
		} else if (v == lwMost) {
			menu.setHeaderTitle(listRaMost.get(info.position).getName());
			if (!datasource
					.DoesFavExists(listRaMost.get(info.position).getId())) {
				menu.add(Menu.NONE, ADD_RADIO_TO_FAV_LWMOST, 0,
						getString(R.string.addToFav));
			} else {
				menu.add(Menu.NONE, DELETE_RADIO_FROM_FAV_LWMOST, 1,
						getString(R.string.deleteFromFav));
			}
		} else if (v == lwFav) {
			menu.setHeaderTitle(listRaFav.get(info.position).getName());
			menu.add(Menu.NONE, DELETE_RADIO_FROM_FAV_LWFAV, 0,
					getString(R.string.deleteFromFav));
		} else if (v == lwSearch) {
			menu.setHeaderTitle(listRaSearch.get(info.position).getName());
			if (!datasource.DoesFavExists(listRaSearch.get(info.position)
					.getId())) {
				menu.add(Menu.NONE, ADD_RADIO_TO_FAV_LWSEARCH, 0,
						getString(R.string.addToFav));
			} else {
				menu.add(Menu.NONE, DELETE_RADIO_FROM_FAV_LWSEARCH, 1,
						getString(R.string.deleteFromFav));
			}
		}
		datasource.Close();
	}

	// When holding down on a ListView item, a dialog will show, giving the
	// option to add that radio to favorites (or remove if already there).
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		datasource.Open();

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case ADD_RADIO_TO_FAV_LWALL:
			try {
				datasource.InsertToFav(listRa.get(info.position));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			datasource.Close();
			return super.onContextItemSelected(item);

		case DELETE_RADIO_FROM_FAV_LWALL:
			datasource.RemoveFromFav(listRa.get(info.position).getId());
			datasource.Close();
			return super.onContextItemSelected(item);

		case ADD_RADIO_TO_FAV_LWMOST:
			try {
				datasource.InsertToFav(listRaMost.get(info.position));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			datasource.Close();
			return super.onContextItemSelected(item);

		case DELETE_RADIO_FROM_FAV_LWMOST:
			datasource.RemoveFromFav(listRaMost.get(info.position).getId());
			datasource.Close();
			return super.onContextItemSelected(item);
		case DELETE_RADIO_FROM_FAV_LWFAV:
			datasource.RemoveFromFav(listRaFav.get(info.position).getId());
			try {
				listRaFav.clear();
				listRaFav.addAll(datasource.SelectFavRadiosFromDB());
			} catch (Exception e) {
				e.printStackTrace();
			}
			adapterFav.notifyDataSetChanged();
			datasource.Close();
			return super.onContextItemSelected(item);
		case ADD_RADIO_TO_FAV_LWSEARCH:
			try {
				datasource.InsertToFav(listRaSearch.get(info.position));
			} catch (Exception e) {
				e.printStackTrace();
			}
			datasource.Close();
			return super.onContextItemSelected(item);
		case DELETE_RADIO_FROM_FAV_LWSEARCH:
			if (!searchGlobal) {
				datasource.RemoveFromFav(listRaSearch.get(info.position)
						.getId());
				datasource.Close();
				return super.onContextItemSelected(item);
			} else {
				// DO SOME STUFF IN HERE FUCKER !!!
			}
		default:
			datasource.Close();
			return super.onContextItemSelected(item);
		}

	}

	// creates options button functionality.
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.settings, menu);
		return true;
	}

	// Nothing
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	// Nothing
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	// When text in entered in the search field with more than 3 chars and
	// nothing more is written for 500ms a search is done.
	@Override
	public void afterTextChanged(final Editable arg0) {

		handlerSearch.removeCallbacksAndMessages(null);
		handlerSearch.postDelayed(new Runnable() {
			public void run() {

				if (arg0.length() >= 2) {
					if (!searchGlobal) {
						searchLocal();
					} else {
						searchGlobal();
					}
				} else if (arg0.length() < 2) {
					if (listRaSearch.size() > 0) {
						listRaSearch.clear();
						adapterSearch.notifyDataSetChanged();
					}
				}
			}
		}, 500);
	}

	// //////////////////////////
	// ON CREATE STUFF //////////
	// //////////////////////////

	// Run onCreate. Initializes all views.
	private void initViews() {

		tabHost = (TabHost) findViewById(android.R.id.tabhost);
		lwAll = (ListView) findViewById(R.id.lwAll);
		lwMost = (ListView) findViewById(R.id.lwMost);
		lwFav = (ListView) findViewById(R.id.lwFav);
		lwSearch = (ListView) findViewById(R.id.lwSearch);
		play = (ImageButton) findViewById(R.id.cmdPlay);
		stop = (ImageButton) findViewById(R.id.cmdStop);
		cmdSwitchGlobal = (ImageButton) findViewById(R.id.cmdGlobal);
		nowPlaying = (TextView) findViewById(R.id.txtNowPlayng);
		textBoxStat = (TextView) findViewById(R.id.textBoxStat);
		imgLoading = (ImageView) findViewById(R.id.imgLoading);
		txtSearch = (EditText) findViewById(R.id.txtSearch);
		controlsBar = (RelativeLayout) findViewById(R.id.controlsBar);
		activityRootView = (View) findViewById(R.id.activityRoot);
		//songProgressBar = (ViewGroup) findViewById(R.id.songProgressBar);
		/*songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
        songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);*/
	}

	// Run onCreate. Sets up all tabs.
	private void setUpTabs() {
		tabHost.setup();

		TabSpec spec1 = tabHost.newTabSpec("TAB 1");
		spec1.setContent(R.id.tab_1);
		spec1.setIndicator("", getResources().getDrawable(R.raw.home));


		TabSpec spec2 = tabHost.newTabSpec("TAB 2");
		spec2.setContent(R.id.tab_2);
		spec2.setIndicator("", getResources().getDrawable(R.raw.most));

		TabSpec spec3 = tabHost.newTabSpec("TAB 3");
		spec3.setContent(R.id.tab_3);
		spec3.setIndicator("", getResources().getDrawable(R.raw.favorites));

		TabSpec spec4 = tabHost.newTabSpec("TAB 4");
		spec4.setContent(R.id.tab_4);
		spec4.setIndicator("", getResources().getDrawable(R.raw.search_icon));
		
		tabHost.addTab(spec1);
		tabHost.addTab(spec2);
		tabHost.addTab(spec3);
		tabHost.addTab(spec4);
		
		for (int i=0; i<tabHost.getTabWidget().getTabCount(); i++)
	    {
			tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 150;
			tabHost.getTabWidget().getChildAt(i).getLayoutParams().width = 150;
	    }
		
		tabHost.setOnTabChangedListener(this);
		setTabColor();
	}

	// Run onCreate. Initializes all data.
	private void initData() {
		playerService = new Intent(this, RadioService.class);
		datasource = new CommentsDataSource(this.getApplicationContext());
		
		//Bug fix: get data from db again, if list is empty
		//TODO: Find out why listRa is sometimes empty 
		if (listRa == null) {
			datasource.Open();
			try {
			listRa = datasource.SelectRadiosFromDB();
			} catch (Exception e) {
				e.printStackTrace();
			}
			datasource.Close();	
		} 
	
		list = listRa;
		List<Radio> radioList = new ArrayList<Radio>(listRa);
		listRaSearch = new ArrayList<Radio>();
		imgLoading.setBackgroundResource(R.layout.movie);
		anim = (AnimationDrawable) imgLoading.getBackground();
		if(radioList.size() < count){
			adapterAll = new RadioAdapter(this, R.layout.listview_item_row,
					radioList);
			
		} else {
			adapterAll = new RadioAdapter(this, R.layout.listview_item_row,
					radioList.subList(0, count));
		}
		adapterMost = new RadioAdapter(this, R.layout.listview_item_row,
				listRaMost);
		adapterFav = new RadioAdapter(this, R.layout.listview_item_row,
				listRaFav);
		adapterSearch = new RadioAdapter(this, R.layout.listview_item_row,
				listRaSearch);

		count = count + 20;
		lwAll.setAdapter(adapterAll);
		lwMost.setAdapter(adapterMost);
		lwFav.setAdapter(adapterFav);
		lwSearch.setAdapter(adapterSearch);
		lwAll.setOnScrollListener(this);
		txtSearch.setOnKeyListener(this);
		txtSearch.addTextChangedListener(this);
		
		//TODO: Not work yet!!
		// Addmob not show when keyboard is shown
		txtSearch.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if (((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).isActive()) {
					hideAddmob();
				}
				else showAddmob();
				
			}
		});
		
		imgLoading.setVisibility(View.GONE);
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(this);
		ListViewOnClick();
		registerForContextMenu(lwAll);
		registerForContextMenu(lwMost);
		registerForContextMenu(lwFav);
		registerForContextMenu(lwSearch);

		PreferenceManager.setDefaultValues(this, R.xml.settings, false);
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		searchGlobal = prefs.getBoolean("global_search_on_off", false);
		if (searchGlobal) {
			cmdSwitchGlobal.setBackgroundResource(R.raw.global_icon);
		} else {
			cmdSwitchGlobal.setBackgroundResource(R.raw.global_icon_gray);
		}
		
		//songProgressBar.setOnSeekBarChangeListener(this); // Important
		
        
	}

	// Run onCreate. Updates UI to match all conditions.
	private void uiUpdate() {
		if (listRaFav.size() > 0) {
			tabHost.setCurrentTab(2);
		}
		datasource.Open();
		if (datasource.GetTheNameOfTheRadiostationThatIsPlaying() != null) {
			nowPlaying.setText(datasource
					.GetTheNameOfTheRadiostationThatIsPlaying());
		}
		if (isRadioServiceRunning(this) == true) {
			play.setVisibility(View.GONE);
			textBoxStat.setText(getString(R.string.textBoxStatPlay));
		} else {
			stop.setVisibility(View.GONE);
			textBoxStat.setText(getString(R.string.textBoxStatStop));
		}
		datasource.Close();
	}

	@Override
	public void onGlobalLayout() {
		int heightDiff = activityRootView.getRootView().getHeight()
				- activityRootView.getHeight();
		if (heightDiff > 220) { // if more than 100 pixels, its probably a
								// keyboard...
			controlsBar.setVisibility(View.GONE);
		} else {
			controlsBar.setVisibility(View.VISIBLE);
		}
	}
/*
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}*/
}